package utils

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"hash"
	"io"
	"math/rand"
	"strconv"
	"time"
)

type Sha1Stream struct{
	_sha1 hash.Hash
}

func (obj *Sha1Stream)Update(data []byte){
	if obj._sha1 == nil{
		obj._sha1 = sha1.New()
	}
	obj._sha1.Write(data)
}

func (obj *Sha1Stream)Sum() string{
	return hex.EncodeToString(obj._sha1.Sum([]byte("")))
}

func Sha1(data []byte) string{
	_sha1 := sha1.New()
	_sha1.Write(data)
	return hex.EncodeToString(_sha1.Sum([]byte("")))
}

// FileSha1 计算文件的 SHA1 哈希值
func FileSha1(reader io.Reader) (string, error) {
	hasher := sha1.New()
	_, err := io.Copy(hasher, reader)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(hasher.Sum(nil)), nil
}

// MD5 计算字符串的 MD5 哈希值
func MD5(data []byte) string {
	hash := md5.Sum(data)
	return hex.EncodeToString(hash[:])
}
func GenerateGroupID() string {
	randomStr := GenerateRandomString(8)
	hash := md5.Sum([]byte(randomStr))
	return hex.EncodeToString(hash[:])[:12]
}

func GenerateFileHash(path string) string {
	hash := md5.Sum([]byte(path + strconv.FormatInt(time.Now().Unix(), 10)))
	return hex.EncodeToString(hash[:])
}

func GenerateHash(reader io.Reader) (string, error) {
	hasher := sha1.New()
	_, err := io.Copy(hasher, reader)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(hasher.Sum(nil)), nil
}

func GenerateRandomString(n int) string {
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	ret := make([]byte, n)
	for i := range ret {
		ret[i] = letters[rand.Intn(len(letters))]
	}
	return string(ret)
}



